<?php

namespace app\admin\controller\facrm\workweixin;

use app\admin\model\Admin;
use app\common\controller\Backend;
use EasyWeChat\Factory;

use  app\admin\model\facrm\qywx\User as QywxUser;
use fast\Random;
use think\Db;
use think\Exception;
use EasyWeChat\Kernel\Support;
use think\Session;

/**
 * 微信管理首页
 * @Internal
 * @icon fa fa-circle-o
 */
class Index extends Backend
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $layout = '';
    protected $app = null;//EasyWeChat 实列
    protected $config = array();//企业微信配置

    public function _initialize()
    {
        parent::_initialize();
        $this->request->filter(['strip_tags']);

        $key = "work_weixin_set";
        $settingModel = new \app\admin\model\facrm\Setting();
        $row = $settingModel->where('key', $key)->find();
        if (!$row) $this->error(__("企业微信未配置"));
        $this->config = json_decode($row['values'], true);//获取器不知道为什么失效了
        if (!$this->config) $this->error(__("企业微信未配置1"));

    }

    /**
     * 微信查看crm客户页
     * @Internal
     */
    public function index()
    {

        if (!$this->auth->isLogin()) {

            $this->redirect(url('facrm/workweixin.index/login', ['url' => url('facrm/workweixin.index/index')]));
        }

        $config = [
            'corp_id' => $this->config['corp_id'],
            'agent_id' => $this->config['agent_id'],
            'secret' => $this->config['customer_secret'],
        ];
        $this->app = $app = Factory::work($config);
        $wx_config = ($app->jssdk->buildConfig(['updateAppMessageShareData', 'updateTimelineShareData'], $debug = false, $beta = false, $json = true, $openTagList = []));

        $app_ag_config = [
            'corp_id' => $this->config['corp_id'],
            'agent_id' => $this->config['agent_id'],
            'secret' => $this->config['agent_secret'],
        ];

        $this->app = $app = Factory::work($app_ag_config);
        $supportExtend = new \addons\facrm\library\extend\easywechat\SupportExtend($app);
        $ag_config = $supportExtend->buildAgentConfig(
            ['getCurExternalContact'],
            $this->config['agent_id'],
            $debug = false,
            $beta = false,
            $json = true,
            $openTagList = []
        );


        $this->view->assign("wx_config", $wx_config);
        $this->view->assign("ag_config", $ag_config);
        return $this->view->fetch();
    }


    /**
     * 获取有用户唯一ID
     * @Internal
     */
    public function getCustomerId()
    {
        $admin = $this->auth->getUserInfo();
        if (!$admin) $this->error(__("未登录"));

        $external_userid = $this->request->param('userid');
        if (!$external_userid) $this->error(__("userid不能为空"));

        //获取本地微信外部联系人customer_id;
        $contactsModel = new \app\admin\model\facrm\qywx\Contacts();

        $qywxContacts = $contactsModel->getContacts($external_userid, $this->config, ['admin_id' => $admin['id']]);
        if (!$qywxContacts) {
            $this->error(__("获取企业客户信息失败"));
        }
        $this->success('', '', $qywxContacts->customer_id);
    }


    /**
     *企业微信登录
     * @Internal
     */
    public function login()
    {
        $url = $this->request->request('url', $this->request->server('HTTP_REFERER', '/'), 'trim');
        if ($url) {
            Session::set("redirecturl", $url);
        }

        //判断是否登录，如果登录直接返回上页面
        if ($this->auth->isLogin()&&$url) {
            $this->redirect($url);
        }


        $callbackUrl = url('facrm/workweixin.index/callback', $vars = [], $suffix = true, $domain = true); // 需设置可信域名
        $app_ag_config = [
            'corp_id' => $this->config['corp_id'],
            'agent_id' => $this->config['agent_id'],
            'secret' => $this->config['agent_secret'],
            'oauth' => ['scopes' => "snsapi_privateinfo"],
        ];

        $app = Factory::work($app_ag_config);
        // 返回一个 redirect 实例
        $app->oauth->setAgentId($this->config['agent_id']);
        $redirect = $app->oauth->redirect($callbackUrl);

        // 直接跳转到企业微信授权
        $redirect->send();
    }

    /**
     * 企业微信登录回调
     * @Internal
     */
    public function callback()
    {
        $app_ag_config = [
            'corp_id' => $this->config['corp_id'],
            'agent_id' => $this->config['agent_id'],
            'secret' => $this->config['agent_secret'],

        ];
        // 获取企业微信用户信息
        $app = Factory::work($app_ag_config);
        $qywx_user = $app->oauth->setAgentId($this->config['agent_id'])->detailed()->user();
        $userid = $qywx_user->getId(); // 对应企业微信英文名（userid）
        if (!$userid) $this->error(__("获取企业微信信息失败"));
        $qywx_user=$qywx_user->toArray();

        $loca_user = QywxUser::getUser($userid);
        if (!$loca_user) {
            $insert_data=[
                'userid'=>$userid,
                'name'=>isset($qywx_user['name'])?$qywx_user['name']:'',
                'mobile'=>isset($qywx_user['mobile'])?$qywx_user['mobile']:'',
                'email'=>isset($qywx_user['email'])?$qywx_user['email']:'',
                'avatar'=>isset($qywx_user['avatar'])?$qywx_user['avatar']:'',
                'gender'=>isset($qywx_user['gender'])?$qywx_user['gender']:'',
                'position'=>isset($qywx_user['position'])?$qywx_user['position']:'',
                'qr_code'=>isset($qywx_user['qr_code'])?$qywx_user['qr_code']:'',
                'status'=>isset($qywx_user['status'])?$qywx_user['status']:'',
            ];

            $loca_user = QywxUser::getUser($userid, $this->config, $insert_data);
        }

        if (!$loca_user || !$loca_user['admin_id']) {
            $this->error(__("企业微信登录失败"));
        }

        $admin = Admin::get($loca_user['admin_id']);
        if (!$admin) {
            $this->error(__("企业微信登录失败:后账帐号不存在"));
        }
        if ($admin['status'] == 'hidden') {
            $this->error(__("企业微信登录失败:后台帐号已经隐藏"));
        }
        $admin->logintime = time();
        $admin->loginip = request()->ip();
        Session::set("admin", $admin->toArray());
        if (method_exists($this->auth, 'getEncryptSafecode')){
            Session::set("admin.safecode", $this->auth->getEncryptSafecode($admin));
        }


        $admin->save();

        //跳转回
        // 成功后返回之前页面
        $url = Session::get("redirecturl") ? Session::get("redirecturl") : url('facrm/workweixin.index/index');
        $this->redirect($url);
        exit();
    }


}